from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet

from django_redis import get_redis_connection

from goods.models import SKU
from goods.serializers import SKUSerializer

from users import constants
from users.models import User
from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer, AddressViewSerializer, \
    AddressTitleSerializer, HistoryViewSerializer


class AddressViewSet(CreateModelMixin, GenericViewSet, UpdateModelMixin):
    '''用户收货地址管理'''
    # 仅认证用户可以访问该视图
    permission_classes = (IsAuthenticated,)
    serializer_class = AddressViewSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        '''地址的新增'''
        # 判断用户的收货地址数量
        count = request.user.addresses.filter(is_deleted=False).count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '收货地址超过上限'})
        # # 创建序列化器
        # serializer = self.get_serializer(data=request.data)
        #
        # # 校验参数
        # serializer.is_valid()
        #
        # # 保存数据
        # serializer.save()
        #
        # # 返回响应
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

        # 调用createmodelmixin中的create方法
        return super().create(request)

    def list(self, request):
        # 查询用户的所有地址病序列化返回
        user = request.user

        queryset = self.get_queryset()

        serializer = self.get_serializer(queryset, many=True)

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # def update(self, request, pk):
    #     '''修改用户地址'''
    #     # 获取用户的地址
    #     address = self.get_object()
    #     # 创建序列化器对象
    #     serializer = self.get_serializer(address)
    #     # 校验参数
    #     serializer.is_valid()
    #     # 保存
    #     serializer.save()
    #     # 返回响应
    #     return Response({'message': 'OK'}, status=status.HTTP_204_NO_CONTENT)

    def destroy(self, request, pk):
        '''删除用户地址'''
        # 获取用户的地址
        address = self.get_object()

        user = request.user
        user.is_deleted = True
        user.save()

        return Response({'message': 'OK'}, status=status.HTTP_204_NO_CONTENT)

    # 设置默认地址
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        '''
        修改默认地址
        url put/addresses/(?P<pk>\d+)/status/
        '''
        # 获取指定的地址
        address = self.get_object()
        # 获取用户
        user = request.user
        # 修改用户的默认地址字段
        user.default_address = address
        # 保存数据
        user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        '''
        修改地址标题
        url put/addresses/(?P<pk>\d+)/title/
        '''
        # 获取地址对象
        address = self.get_object()
        # 创建序列器对象
        serializer = AddressTitleSerializer(address, data=request.data)
        # 校验参数(是否存在)
        serializer.is_valid()
        # 保存数据
        serializer.save()
        # 返回响应
        return Response(serializer.data)


# 判断用户名是否存在
class UsernamecountView(APIView):
    '''
    判断用户是否存在,根据查询用户在数据库中的数量,如果不存在就为0
    '''

    def get(self, request, username):
        '''
        url :GET /usernames/(?P<username>\w{5,20})/count/
        :param request: GET
        :param username: url传递参数
        :return: 响应
        '''
        # 查询用户名在数据库中的数量
        count = User.objects.filter(username=username).count()

        # 封装为字典
        data = {
            'username': username,
            'count': count
        }

        # 返回响应
        return Response(data)


# 判断手机号是否存在
class UsermobilecountView(APIView):
    '''
    判断用户手机号是否存在,根据查询用户手机号在数据库中的数量,如果不存在就为0
    '''

    def get(self, request, mobile):
        '''
        url: GET/mobiles/(?P<mobile>1[3-9]\d{9})/count/
        :param request: GET
        :param mobile: url传递参数
        :return: mobile count
        '''
        # 查询手机号在数据库中的数量
        count = User.objects.filter(mobile=mobile).count()

        # 封装字典
        data = {
            'mobile': mobile,
            'count': count
        }

        # 返回响应
        return Response(data)


# 注册的实现
class UserView(CreateAPIView):
    ''' 用户的注册 '''
    serializer_class = UserSerializer


# 用户个人中心信息的展示
class UserDetailView(RetrieveAPIView):
    # 设置权限,仅认证用户可以访问该视图
    permission_classes = (IsAuthenticated,)
    serializer_class = UserDetailSerializer

    def get_object(self):
        # 如果视图中的方法没有传request,可以使用self的request属性来获取参数
        user = self.request.user
        return user

    # def get(self, request):
    #     # 获取用户
    #     user = request.user
    #
    #     # 创建序列化器对象
    #     serializer = self.get_serializer(user)
    #
    #     # 返回响应
    #     return Response(serializer.data, status=status.HTTP_200_OK)


# 用户邮箱的设置
class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        user = self.request.user
        return user
    #
    # def put(self, request):
    #     # 获取用户
    #     user = request.user
    #     # 创建序列化器对象
    #     serializer = self.get_serializer(user, data=request.data)
    #     # 校验参数
    #     serializer.is_valid(raise_exception=True)
    #     # 保存
    #     serializer.save()
    #     # 返回响应
    #     return Response(serializer.data, status=status.HTTP_200_OK)


# /emails/verification/?token=xxx
class EmailVerifyView(APIView):
    '''邮件验证'''

    # 获取参数校验参数
    def put(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 校验token
        user = User.check_verify_email_url(token)

        if not user:
            return Response({'message': '无效的验证连接'}, status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


# 用户的浏览记录
class HistoryView(CreateAPIView):
    '''用户的浏览记录'''
    permission_classes = [IsAuthenticated]
    serializer_class = HistoryViewSerializer

    # def post(self, request):
    #     '''用户的浏览记录存储
    #     POST /browse_histories/
    #     '''
    #     # 创建序列化器对象
    #     serializer = self.get_serializer(data=request.data)
    #     # 校验参数
    #     serializer.is_valid(raise_exception = True)
    #     # 保存数据
    #     serializer.save()
    #
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get(self, request):
        '''获取用户的浏览记录'''
        # 获取用户对象
        user = request.user
        # 从reids中获取所有记录
        redis_conn = get_redis_connection('history')
        skus_id = redis_conn.lrange('history_%s' % user.id, 0, -1)

        his_list = []
        for sku_id in skus_id:
            sku = SKU.objects.get(id=sku_id)
            his_list.append(sku)
        # 将列表传入序列化器进行序列化,list 类似queryset,也可以直接进行序列化
        serializer = SKUSerializer(his_list, many=True)
        # 返回响应
        return Response(serializer.data, status=status.HTTP_200_OK)
